var db = require('../db/index')
const util = require('util');
// const query = util.promisify(db.query).bind(db)
const query = util.promisify(db.query).bind(db)
exports.getGoods = async(req, res) => {
    //接收数据，get 请求数据 如果是post请求 req.body
    // console.log(req.query);
    //获取关键字
    const keyword = req.query.query;
    const page_size = req.query.pagesize; //每页显示的条数
    const page_num = req.query.pagenum; //当前的页码数
    if (page_size == '' || page_num == '') {
        res.ResData("参数错误")
    }
    try {
        //计算总条数
        var sqlTotal = "select count(*) as num from sp_goods "
        if (keyword) {
            sqlTotal += "where goods_name like '%" + keyword + "%'";
        }
        var total = await query(sqlTotal);
        // console.log(total[0]);
        total = total[0]['num'];
        if (page_num > Math.ceil(total / page_size)) {
            page_num = Math.ceil(total / page_size)
        }
        var sql = "select * from sp_goods "
        if (keyword) {
            sql += "where sp_goods.goods_name like '%" + keyword + "%'limit ?,?"
        } else {
            sql += "limit ?,?"
        }
        var params = [(parseInt(page_num) - 1) * parseInt(page_size), parseInt(page_size)]
        var result = await query(sql, params);
        //组合返回数据
        var retgoods = []
        for (idx in result) {
            var goods = result[idx];
            // var goods_name = goods.goods_name
            retgoods.push({
                'goods_id': goods.goods_id,
                'goods_name': goods.goods_name,
                'goods_price': goods.goods_price,
                'goods_number': goods.goods_number,
                'goods_weight': goods.goods_weight,
                'goods_state': goods.goods_state == 1,
                'add_time': goods.add_time,
                'upd_time': goods.upd_time,
                'hot_mumber': goods.hot_mumber,
                'is_promote': goods.is_promote,
            })
        }
        const data = {
            "total": total,
            "pagenum": page_num,
            "goods": retgoods,
        }
        res.ResData("获取用户列表成功", 200, data)
    } catch (err) {
        res.ResData(err)
    }

}